<?php

namespace App\Console\Commands\Clickhouse;

use App\Models\Clickhouse\Guanyuan\GyCloseShopCHModel;
use App\Remote\Guanyuan\GuanyuanRemote;
use App\Remote\Guanyuan\GuanyuanRetry\GuanyuanRetryRemote;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;

class SysGyCloseShopCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'clickhouse:sys:gyCloseShop';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步观远闭店门店数据到clickhouse';

    protected int $id;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws GuzzleException
     */
    public function handle(): int
    {
        try {
            $fields = [
                "berthNumber",
                "status",
                "typeOfOperation",
                "shopType",
                "cashRegisterSystem",
                "storeProvince",
                "storeLocation",
                "subsidiaryCompany",
                "storeName",
                "shopAddress",
                "openingDate",
                "closingTime",
                "franchiseFee",
                "technologyTransferFee",
                "managementFee",
                "area",
                "rent",
                "labour",
                "sourceOfEnergy",
                "franchisee",
                "numberOfEmployees",
                "districtOrCounty",
                "region",
                "reasonForClosing",
                "contractCommencementDate",
                "contractEndDate",
                "franchiseeRealName",
                "cityClass",
                "subState",
                "secondaryState",
                "estimatedOpeningTime",
                "confirmSiteLocationTime"
            ];


            $this->id = 0;

            $data = GuanyuanRetryRemote::sourceData(
                'd4e637ebdbb154560ad54721',
                'c636d049c8ad6475987065db',
                []
            );

            if (empty($data["data"])) {
                //执行脚本日期 == 拉取观远数据日期 数据为空此时为异常状态
                throw new \Exception("观远拉取闭店门店数据异常");
            }

            $this->getOutput()->info(
                "正在执行...  [内存占用:  " . (memory_get_usage(true) / 1024 / 1024) . "MB ]"
            );

            $this->getOutput()->info("门店总量 :  " . count($data["data"] ?? []));
            $batchInsert = [];
            collect($data["data"])->each(function ($row) use (
                $fields,
                &$batchInsert
            ) {
                collect($row)->each(function ($value, $key) use ($fields, &$insert, &$batchInsert) {
                    if (isset($fields[$key])) {
                        $insert[$fields[$key]] = $value;
                    } else {
                        return false;
                    }
                });

                $this->id = $this->id + 1;
                array_push($batchInsert, array_merge(
                    $insert, [
                    "createdAt" => time(),
                    "id"        => $this->id,
                    "updatedAt" => 0
                ]));
            });


            if ($batchInsert) {
                GyCloseShopCHModel::query()->where("id", ">", 0)->delete();

                collect($batchInsert)->chunk(500)->each(function (Collection $collection) {
                    GyCloseShopCHModel::query()->insert($collection->values()->toArray());
                });
            }

            logInfo("{$this->description} 成功", collect([]), true, false);
        } catch (\Exception $exception) {
            logException("{$this->description} 失败 : {$exception->getMessage()}", $exception, null, true, true);
        }
        return 0;
    }
}
